<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
class CommonService{
	
    function show($code = 1, $msg = '', $data = []){
    	return array('code'=>$code,'msg'=>$msg,'data'=>$data);
    }
    
    /**
     * 原生查询
     */
    function selectSql($sql){
    	try{
    		$result = DB::select($sql);
	    	if(count($result) != 0){
	            return $this->show(1,'查询成功',$result);
	        }else{
	            return $this->show(0,'查询失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
    /**
     * 原生插入
     */
    function insertSql($sql){
    	try{
    		$result = DB::insert($sql);
	    	if($result){
	            return $this->show(1,'添加成功',$result);
	        }else{
	            return $this->show(0,'添加失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
     /**
     * 原生更新
     */
    function updateSql($sql){
    	try{
    		$result = DB::update($sql);
	    	if($result){
	            return $this->show(1,'更新成功',$result);
	        }else{
	            return $this->show(0,'更新失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
     /**
     * 原生删除
     */
    function delelteSql($sql){
    	try{
    		$result = DB::delete($sql);
	    	if($result){
	            return $this->show(1,'添加成功',$result);
	        }else{
	            return $this->show(0,'删除失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
    /**
     * 连表查询
     */
    function joinSql($l_table,$r_table,$l_field,$j_where,$r_field){
    	try{
    		$result = DB::table($l_table)->join($r_table,$l_field,$j_where,$r_field)->select("article_news.*","article_cate.title as cate_title")->get();
	    	if(count($result) != 0){
	            return $this->show(1,'查询成功',$result);
	        }else{
	            return $this->show(0,'查询失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    	 
    }
    
    /**
     * 递增
     */
    
    function increSql($table,$field = 'id',$value = 1){
    	try{
    		$result = DB::table($table)->increment($field, $value);
	    	if($result){
	            return $this->show(1,'更新成功',$result);
	        }else{
	            return $this->show(0,'更新失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
    /**
     * 递减
     */
    function decreSql($table,$field = 'id',$value = 1){
    	try{
    		$result = DB::table($table)->decrement($field, $value);
	    	if($result){
	            return $this->show(1,'更新成功',$result);
	        }else{
	            return $this->show(0,'更新失败',$result);
	        }
		}catch(\Exception $e){
	    	return $this->show(2,'系统错误',$e);
	    }
    }
    
}
